import FormModal from '@/components/FormModal/index.jsx';
import { Form, Input, Radio } from 'antd';
import { forwardRef, useImperativeHandle, useRef, useState } from 'react';
import { PermissionApi } from '@/api/permission/api.js';
import ModalUtil from '@/utils/modal.js';

function PermissionFormModal({ onRefresh }, ref) {
  useImperativeHandle(ref, () => ({
    openEdit: (data) => openEdit(data),
    openAdd: () => openAdd(),
    close: () => formRef.current?.close()
  }));

  const [form] = Form.useForm();
  const [isEdit, setIsEdit] = useState(false);
  const formRef = useRef(null);
  const [updateId, setUpdateId] = useState();

  // 打开编辑弹窗
  function openEdit(data) {
    setIsEdit(true);
    if (data.permissionId == null) {
      setIsEdit(false);
      ModalUtil.error('数据ID丢失，请刷新重试');
      return;
    }
    setUpdateId(data.permissionId);
    formRef.current?.open();
    form.setFieldsValue(data);
  }

  // 打开新增弹窗
  function openAdd() {
    setIsEdit(false);
    formRef.current?.open();
    form?.resetFields();
  }

  // 提交表单
  const handleSubmit = async (values) => {
    let isSuccess = false;
    if (isEdit) {
      const { code } = await PermissionApi.update(updateId, values);
      if (code === 0) {
        isSuccess = true;
      }
    } else {
      const { code } = await PermissionApi.add(values);
      if (code === 0) {
        isSuccess = true;
      }
    }
    if (isSuccess) {
      ModalUtil.success('操作成功');
      form?.resetFields();
      onRefresh && onRefresh();
      formRef.current?.close();
    }
  };

  return (
    <FormModal
      form={form}
      ref={formRef}
      name="permissionForm"
      title={isEdit ? '编辑权限' : '新增权限'}
      onFinish={handleSubmit}
      formItems={
        <>
          <Form.Item
            name="permissionName"
            label="权限名称"
            rules={[{ required: true, message: '请输入权限名称' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="permissionCode"
            label="权限代码"
            rules={[{ required: true, message: '请输入权限代码' }]}
          >
            <Input disabled={isEdit} />
          </Form.Item>
          <Form.Item
            name="permissionDesc"
            label="权限说明"
            rules={[{ required: true, message: '请输入权限说明' }]}
          >
            <Input.TextArea />
          </Form.Item>
          <Form.Item
            name="status"
            label="状态"
            rules={[{ required: true, message: '请选择状态' }]}
            initialValue="1"
          >
            <Radio.Group
              options={[
                { label: '启用', value: '1' },
                { label: '禁用', value: '2' }
              ]}
              optionType="button"
              buttonStyle="solid"
            />
          </Form.Item>
        </>
      }
    />
  );
}

export default forwardRef(PermissionFormModal);
